package com.yu.alimsg;

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@AllArgsConstructor
public class MsgUtils {
    private String accessKeyId;
    private String accessKeySecret;
    private String smsCode; // 模板代码
    private String signName; // 签名名称

    public void sendMsg(String phone, String code) {
        try {
            Config config = new Config()
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);
            // 配置 Endpoint
            config.endpoint = "dysmsapi.aliyuncs.com";

            Client client = new Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(signName)
                    .setTemplateCode(smsCode)
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

            log.info("短信发送成功: {}", Common.toJSONString(sendSmsResponse));
        } catch (TeaException e) {
            log.error("短信发送失败: {}", e.getMessage(), e);
            // 根据需要抛出异常或进行其他处理
            throw new RuntimeException(e);
        } catch (Exception e) {
            log.error("发生未知错误: {}", e.getMessage(), e);
            // 处理其他类型的异常
            throw new RuntimeException(e);
        }
    }
}
